package edu.ccut.saturn.studio.wfg.dialog.autoactivitydialog;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;


import edu.ccut.saturn.studio.Activator;
import edu.ccut.saturn.studio.Images;
import edu.ccut.saturn.studio.core.util.eclipse.Messages;
import edu.ccut.saturn.studio.wfg.dialog.RevertCandidate;
import edu.ccut.saturn.studio.wfg.dialog.SelectionCandidate;
import edu.ccut.saturn.studio.wfg.dialog.TableViewerContentProvider;
import edu.ccut.saturn.studio.wfg.dialog.vocationallogicdialog.LogicKeyAttributeLabelProvider;
import edu.ccut.saturn.studio.wfg.dialog.vocationallogicdialog.SaturnVocationalLogicDialogForAdd;
import edu.ccut.saturn.studio.wfg.dialog.vocationallogicdialog.SaturnVocationalLogicDialogForEdit;
import edu.ccut.saturn.studio.wfg.wfgmodel.LogicKeyAttribute;
import edu.ccut.saturn.studio.wfg.wfgmodel.SaturnAttribute;
import edu.ccut.saturn.studio.wfg.wfgmodel.SaturnAutoActivityNode;

public class SaturnAutoActivityDialog extends TitleAreaDialog {
	
	private SaturnAutoActivityNode saturnAutoActivityNode;
	
	private LogicKeyAttribute logicKeyAttribute;
	
	private List<SaturnAttribute> logicKeyTemp;
	
	// 基本信息
	private Label activityIdLabel, activityNameLabel, polymeModeLabel, descriptionLabel;

	private Text activityIdText, activityNameText, descriptionText;

	private Combo polymeModeCombo;
	
	// logicKey表单信息(触发事件)
	private TableViewer tableViewer;
	
	private Table table;
	
	private Button insertButton, deleteButton, upbutton, downbutton, editButton;

	public SaturnAutoActivityDialog(Shell parentShell, SaturnAutoActivityNode saturnAutoActivityNode) {
		super(parentShell);
		this.saturnAutoActivityNode = saturnAutoActivityNode;
		this.copyLogicKeyList(saturnAutoActivityNode.getLogicList());
	}
	
	protected Control createContents(Composite parent) {
		Control contents = super.createContents(parent);
		setMessage(SelectionCandidate.SETTING_ATTRIBUTE + saturnAutoActivityNode.getName()); 
		return contents;
	}

	@Override
	protected Control createDialogArea(Composite parent) {

		getShell().setText(SelectionCandidate.ATTRIBUTE_SETTING); 
		setTitleImage(Activator.getImage(Images.SATURN_ICONS_MAXNAME));
		Composite area = (Composite) super.createDialogArea(parent);
		
		TabFolder tabFolder;
		tabFolder = new TabFolder(area, SWT.NONE);
		tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH));
		
		// 基本信息选项卡
		final TabItem tabItem = new TabItem(tabFolder, SWT.NONE);
		tabItem.setText(Messages.getString("SaturnAutoActivityDialog.baseInformation"));  //$NON-NLS-1$
		
		final Group group = new Group(tabFolder, SWT.NONE);
		group.setText(Messages.getString("SaturnAutoActivityDialog.BaseInformation")); //$NON-NLS-1$
		tabItem.setControl(group);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 2;
		group.setLayout(gridLayout);
		
		activityIdLabel = new Label(group, SWT.NONE);
		activityIdLabel.setText(Messages.getString("SaturnAutoActivityDialog.ActionID")); //$NON-NLS-1$
		
		activityIdText = new Text(group, SWT.BORDER | SWT.READ_ONLY);
		activityIdText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

		activityNameLabel = new Label(group, SWT.NONE);
		activityNameLabel.setText(Messages.getString("SaturnAutoActivityDialog.ActionName")); //$NON-NLS-1$

		activityNameText = new Text(group, SWT.BORDER);
		activityNameText.setTextLimit(50);
		activityNameText.setFocus();
		activityNameText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

		polymeModeLabel = new Label(group, SWT.NONE);
		polymeModeLabel.setText(Messages.getString("SaturnAutoActivityDialog.PatternClustering")); //$NON-NLS-1$

		polymeModeCombo = new Combo(group, SWT.READ_ONLY);
		polymeModeCombo.setLayoutData(new GridData(80, SWT.DEFAULT));
		polymeModeCombo.setItems(SelectionCandidate.polymeModeCandidate);

		descriptionLabel = new Label(group, SWT.NONE);
		descriptionLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
		descriptionLabel.setText(Messages.getString("SaturnAutoActivityDialog.Description")); //$NON-NLS-1$

		descriptionText = new Text(group, SWT.V_SCROLL | SWT.BORDER | SWT.WRAP);
		descriptionText.setTextLimit(200);
		final GridData gd_descriptionText = new GridData(SWT.FILL, SWT.FILL, true, true);
		gd_descriptionText.heightHint = 70;
		descriptionText.setLayoutData(gd_descriptionText);
		
		// logicKey表单信息选项卡
		final TabItem tabItem_1 = new TabItem(tabFolder, SWT.NONE);
		tabItem_1.setText(Messages.getString("SaturnAutoActivityDialog.TriggerEvent")); //$NON-NLS-1$

		final Group group_1 = new Group(tabFolder, SWT.NONE);
		group_1.setText(Messages.getString("SaturnAutoActivityDialog.Parameter")); //$NON-NLS-1$
		tabItem_1.setControl(group_1);
		final GridLayout gridLayout_1 = new GridLayout();
		group_1.setLayout(gridLayout_1);

		Composite composite1 = new Composite(group_1, SWT.NONE);
		final GridData gd_composite1 = new GridData(SWT.FILL, SWT.FILL, true, true);
		composite1.setLayoutData(gd_composite1);
		composite1.setLayout(new FormLayout());

		tableViewer = new TableViewer(composite1, SWT.MULTI | SWT.FULL_SELECTION | SWT.BORDER);
		table = tableViewer.getTable();
		final FormData fd_table = new FormData();
		fd_table.bottom = new FormAttachment(100, -8);
		fd_table.right = new FormAttachment(100, -100);
		fd_table.top = new FormAttachment(0, 10);
		fd_table.left = new FormAttachment(0, 5);
		table.setLayoutData(fd_table);
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		tableViewer.setContentProvider(new TableViewerContentProvider());
		tableViewer.setLabelProvider(new LogicKeyAttributeLabelProvider());

		final TableColumn newColumnTableColumn = new TableColumn(table,	SWT.NONE);
		newColumnTableColumn.setWidth(390);
		newColumnTableColumn.setText(Messages.getString("SaturnAutoActivityDialog.Expression")); //$NON-NLS-1$

		insertButton = new Button(composite1, SWT.NONE);
		insertButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent selectionevent) {
				openAddDialog();
			}
		});
		final FormData fd_addbutton = new FormData();
		fd_addbutton.bottom = new FormAttachment(table, 23, SWT.TOP);
		fd_addbutton.top = new FormAttachment(table, 0, SWT.TOP);
		fd_addbutton.right = new FormAttachment(100, -20);
		fd_addbutton.left = new FormAttachment(100, -75);
		insertButton.setLayoutData(fd_addbutton);
		insertButton.setText(SelectionCandidate.INSERT_BUTTON);

		deleteButton = new Button(composite1, SWT.NONE);
		deleteButton.addSelectionListener(new SelectionAdapter() {
			@SuppressWarnings("unchecked") //$NON-NLS-1$
			public void widgetSelected(final SelectionEvent e) {
				IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
				logicKeyAttribute = (LogicKeyAttribute) selection.getFirstElement();
				if (selection.isEmpty()) {
					MessageDialog.openInformation(null, SelectionCandidate.HINT, SelectionCandidate.CHOOSE_DELETE_RECORD);
				} else {
					List<SaturnAttribute> logicKeyListForDelete = (List<SaturnAttribute>) tableViewer.getInput();
					logicKeyListForDelete.remove(logicKeyAttribute);
					tableViewer.setInput(logicKeyListForDelete);
				}
			}
		});
		final FormData fd_deletebutton = new FormData();
		fd_deletebutton.top = new FormAttachment(insertButton, 5, SWT.BOTTOM);
		fd_deletebutton.right = new FormAttachment(insertButton, 0, SWT.RIGHT);
		fd_deletebutton.left = new FormAttachment(100, -75);
		deleteButton.setLayoutData(fd_deletebutton);
		deleteButton.setText(SelectionCandidate.DELETE_BUTTON); 

		upbutton = new Button(composite1, SWT.NONE);
		upbutton.addSelectionListener(new SelectionAdapter() {
			@SuppressWarnings("unchecked") //$NON-NLS-1$
			public void widgetSelected(final SelectionEvent e) {
				IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
				if (selection.isEmpty()) {
					MessageDialog.openInformation(null, SelectionCandidate.HINT, SelectionCandidate.CHOOSE_A_RECORD);
				} else {
					Table table_up = tableViewer.getTable();
					if (tableViewer.getTable() != null) {
						int i = table_up.getSelectionIndex();
						if (i > 0) {
							SaturnAttribute lka = logicKeyTemp.get(i);
							List<SaturnAttribute> logicKeyListForUp = (List<SaturnAttribute>) tableViewer.getInput();
							logicKeyListForUp.remove(lka);
							tableViewer.remove(lka);
							logicKeyListForUp.add(i - 1, lka);
							tableViewer.setInput(logicKeyListForUp);
							table_up.setSelection(i - 1);
						}
					}
				}
			}
		});
		final FormData fd_upbutton = new FormData();
		fd_upbutton.top = new FormAttachment(deleteButton, 5, SWT.BOTTOM);
		fd_upbutton.right = new FormAttachment(deleteButton, 0, SWT.RIGHT);
		fd_upbutton.left = new FormAttachment(100, -75);
		upbutton.setLayoutData(fd_upbutton);
		upbutton.setText(SelectionCandidate.UP_BUTTON); 

		downbutton = new Button(composite1, SWT.NONE);
		downbutton.addSelectionListener(new SelectionAdapter() {
			@SuppressWarnings("unchecked") //$NON-NLS-1$
			public void widgetSelected(final SelectionEvent e) {
				IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
				if (selection.isEmpty()) {
					MessageDialog.openInformation(null, SelectionCandidate.HINT, SelectionCandidate.CHOOSE_A_RECORD);  
				} else {
					Table table_down = tableViewer.getTable();
					if (tableViewer.getTable() != null) {
						int i = table_down.getSelectionIndex();
						if (i < tableViewer.getTable().getItemCount() - 1) {
							SaturnAttribute lka = logicKeyTemp.get(i);
							List<SaturnAttribute> logicKeyListForDown = (List<SaturnAttribute>) tableViewer.getInput();
							logicKeyListForDown.remove(lka);
							tableViewer.remove(lka);
							logicKeyListForDown.add(i + 1, lka);
							tableViewer.setInput(logicKeyListForDown);
							table_down.setSelection(i + 1);
						}
					}
				}
			}
		});
		final FormData fd_downbutton = new FormData();
		fd_downbutton.top = new FormAttachment(upbutton, 5, SWT.BOTTOM);
		fd_downbutton.right = new FormAttachment(upbutton, 0, SWT.RIGHT);
		fd_downbutton.left = new FormAttachment(100, -75);
		downbutton.setLayoutData(fd_downbutton);
		downbutton.setText(SelectionCandidate.DOWN_BUTTON); 

		editButton = new Button(composite1, SWT.NONE);
		editButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
				if (selection.isEmpty()) {
					MessageDialog.openInformation(null, SelectionCandidate.HINT, SelectionCandidate.CHOOSE_EDIT_RECORD);  
				} else {
					logicKeyAttribute = (LogicKeyAttribute) selection.getFirstElement();
					openEditDialog(logicKeyAttribute);
					tableViewer.refresh();
				}
			}
		});
		final FormData fd_editbutton = new FormData();
		fd_editbutton.top = new FormAttachment(downbutton, 5, SWT.BOTTOM);
		fd_editbutton.right = new FormAttachment(downbutton, 0, SWT.RIGHT);
		fd_editbutton.left = new FormAttachment(100, -75);
		editButton.setLayoutData(fd_editbutton);
		editButton.setText(SelectionCandidate.EDIT_BUTTON);
		
		initial();
		
		/**
		 * 活动名称不能为空
		 * 
		 * */
		activityNameText.addModifyListener(new ModifyListener() {
			public void modifyText(final ModifyEvent e) {
				if("".equals(activityNameText.getText().trim())){ //$NON-NLS-1$
					setErrorMessage(Messages.getString("SaturnAutoActivityDialog.ActionNameCannotEmpty")); //$NON-NLS-1$
					getButton(IDialogConstants.OK_ID).setEnabled(false);
				} else {
					setErrorMessage(null);
					getButton(IDialogConstants.OK_ID).setEnabled(true);
				}
			}
		});
		
		return area;
	}
	
	@SuppressWarnings("unchecked") //$NON-NLS-1$
	private void openAddDialog(){
		SaturnVocationalLogicDialogForAdd addDialog = new SaturnVocationalLogicDialogForAdd(Display.getDefault().getShells()[0], logicKeyTemp, saturnAutoActivityNode);
		if (addDialog.open() == IDialogConstants.OK_ID) {
			tableViewer.setInput(logicKeyTemp);
		}
	}
	
	@SuppressWarnings("unchecked") //$NON-NLS-1$
	private void openEditDialog(LogicKeyAttribute logicKeyAttribute){
		SaturnVocationalLogicDialogForEdit editDialog = new SaturnVocationalLogicDialogForEdit(Display.getDefault().getShells()[0], logicKeyAttribute, saturnAutoActivityNode);
		editDialog.open();
	}
	
	protected Point getInitialSize() {
		return new Point(540, 480);
	}
	
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText(SelectionCandidate.ATTRIBUTE_SETTING); 
		newShell.setImage(Activator.getImage(Images.SATURN_ICONS_SMALLNAME)); 
	}
	
	protected int getShellStyle() {
		return SWT.CLOSE | SWT.RESIZE;
	}
	
	private void copyLogicKeyList(List<SaturnAttribute> list){
		List<SaturnAttribute> logicKeyTemps = new ArrayList<SaturnAttribute>();
		for(SaturnAttribute saturn : list){
			LogicKeyAttribute logic = new LogicKeyAttribute((LogicKeyAttribute)saturn);
			logicKeyTemps.add(logic);
		}
		this.logicKeyTemp = logicKeyTemps;
	}
	
	private void initial() {
		// 基本信息选项卡
		activityIdText.setText(saturnAutoActivityNode.getId().trim());
		activityNameText.setText(saturnAutoActivityNode.getName().trim());
		descriptionText.setText(saturnAutoActivityNode.getDescription());

		polymeModeCombo.setText(RevertCandidate.revertPolymeMode(saturnAutoActivityNode.getPolymeMode().trim()));
	
		// LogicKey选项卡
		tableViewer.setInput(logicKeyTemp);
	}
	
	@Override
	protected void buttonPressed(int buttonId) {
		if (saturnAutoActivityNode == null) {
			return;
		}
		if (buttonId == IDialogConstants.OK_ID) {
			// 基本信息
			saturnAutoActivityNode.setName(activityNameText.getText().trim());
			saturnAutoActivityNode.setDescription(descriptionText.getText().trim());
			saturnAutoActivityNode.setPolymeMode(RevertCandidate
					.revertFromFaceToVO(polymeModeCombo.getText().trim()));
			
			// logicKey
			saturnAutoActivityNode.setLogicList(logicKeyTemp);
		}
		super.buttonPressed(buttonId);
	}
	
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		super.createButtonsForButtonBar(parent);
		getButton(IDialogConstants.OK_ID).setEnabled(true);
	}
}
